/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;

import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.DefaultListModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import org.math.plot.plots.LinePlot;
import org.math.plot.plots.Plot;
import org.math.plot.utils.Array;
import stendcontrol.Func;

/**
 *
 * @author minaev
 */
public class ViewerFrame extends javax.swing.JFrame {

    TreeModel dt_model;
    ArrayList<TreePath> added_funcs = new ArrayList<TreePath>();
    ArrayList<Plot> plot_added = new ArrayList<Plot>();
    ArrayList<Color> plot_colors = new ArrayList<Color>();
    Random r = new Random();
    //LegendListModel llm = new LegendListModel(added_funcs);
    DefaultListModel<Object> llm = new DefaultListModel<Object>();
    LegendListCellRender llcr = new LegendListCellRender(plot_colors);

    /**
     * Creates new form ViewerFrame
     */
    public ViewerFrame(TreeModel t_mod) {


        MouseListener m_lstr = new MouseListener() {
            @Override
            public void mousePressed(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    int selRow = j_tree.getRowForLocation(e.getX(), e.getY());
                    TreePath selPath = j_tree.getPathForLocation(e.getX(), e.getY());
                    if (selRow != -1) {
                        if (selPath.getPath()[selPath.getPath().length - 1]
                                .getClass() == Func.class) {
                            Func afc =
                                    (Func) selPath.
                                    getPath()[selPath.getPath().length - 1];
                            if (added_funcs.contains(selPath)) {
                                int ind = added_funcs.indexOf(selPath);
                                llm.remove(ind);
                                plot.removePlot(plot_added.get(ind));
                                plot.repaint();
                                added_funcs.remove(ind);
                                plot_added.remove(ind);
                                plot_colors.remove(ind);
                            } else {
                                added_funcs.add(selPath);

                                double[] x = Array.increment(
                                        afc.getValues().length, 1, 1);

                                plot_colors.add(new Color((r.nextInt(192) << 16)
                                        | (r.nextInt(192) << 8)
                                        | r.nextInt(192)));
                                Plot a_plot = new LinePlot(afc.getName(),
                                        plot_colors.get(plot_colors.size() - 1),
                                        Array.mergeColumns(x, afc.getValues()));
                                plot_added.add(a_plot);
                                plot.addPlot(a_plot);
                                String rt_string = "";
                                for (Object obj : selPath.getPath()) {
                                    rt_string += obj.toString() + ">";
                                }
                                rt_string = rt_string.substring(0, rt_string.length() - 1);
                                llm.addElement(rt_string);
                            }
                        }
                        /*System.out.println("___________________________");
                         for (int i = 0; i < selPath.getPath().length; i++) {
                         System.out.println(selPath.getPathComponent(i));
                         }
                         System.out.println("selRow:"+selRow);*/
                        //System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~");

                        /*if (e.getClickCount() == 1) {
                         mySingleClick(selRow, selPath);
                         } else if (e.getClickCount() == 2) {
                         myDoubleClick(selRow, selPath);
                         }*/
                    }
                }
            }

            @Override
            public void mouseClicked(MouseEvent e) {
            }

            @Override
            public void mouseReleased(MouseEvent e) {
            }

            @Override
            public void mouseEntered(MouseEvent e) {
            }

            @Override
            public void mouseExited(MouseEvent e) {
            }
        };
        //j_tree.set



        dt_model = t_mod;

        initComponents();

        j_tree.addMouseListener(m_lstr);



    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        j_tree = new javax.swing.JTree();
        plot = new org.math.plot.Plot2DPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jLstLegend = new javax.swing.JList();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        j_tree.setModel(dt_model);
        jScrollPane1.setViewportView(j_tree);

        jLstLegend.setModel(llm);
        jLstLegend.setCellRenderer(llcr);
        jScrollPane2.setViewportView(jLstLegend);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(plot, javax.swing.GroupLayout.DEFAULT_SIZE, 532, Short.MAX_VALUE)
                    .addComponent(jScrollPane2))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 276, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(plot, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ViewerFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ViewerFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ViewerFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ViewerFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        /*java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
         new ViewerFrame().setVisible(true);
         }
         });*/
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JList jLstLegend;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTree j_tree;
    private org.math.plot.Plot2DPanel plot;
    // End of variables declaration//GEN-END:variables
}
